package com.zdy.im.user.service.impl;


import com.sixeco.framework.common.data.BasePage;
import com.sixeco.framework.common.enums.ResultEnum;
import com.sixeco.framework.core.db.IterableConverter;
import com.sixeco.framework.core.db.ext.Query;
import com.sixeco.framework.http.data.vo.ResponseResultList;
import com.sixeco.framework.util.PageUtils;
import com.sixeco.framework.util.excel.ExcelUtils;
import com.zdy.im.user.dao.ImRoomUserShipDao;
import com.zdy.im.user.dto.request.ImRoomUserShipRequestDto;
import com.zdy.im.user.dto.response.ImRoomUserShipResponseDto;
import com.zdy.im.user.entity.ImRoomUserShip;
import com.zdy.im.user.service.ImRoomUserShipService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.io.InputStream;
import java.util.*;


/**
 * @ClassName: ImRoomUserShipDao.java
 * @Description: 群与用户关系的数据交互处理类
 * @Author 作者 : zdy
 * @CreateDate 创建时间: 2021-02-30
 * @version V1.0.0
 * <p>
 * ----------------------------------------------------------------------------
 *  modifyer    modifyTime                 comment
 *
 * ----------------------------------------------------------------------------
 * </p>
 */
@Service
public class ImRoomUserShipServiceImpl  implements ImRoomUserShipService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ImRoomUserShipDao imRoomUserShipDao;



    /**
     * 保存群与用户关系同时更新数据库和缓存的实现方法
     * @param imRoomUserShipRequestDto ImRoomUserShipResponseDto
     * @return
     */
    public ImRoomUserShipResponseDto saveImRoomUserShip(ImRoomUserShipRequestDto imRoomUserShipRequestDto){
        if(imRoomUserShipRequestDto== null){
            return null;
        }
        ImRoomUserShip imRoomUserShip = ImRoomUserShip.build().clone(imRoomUserShipRequestDto);
        boolean result = imRoomUserShipDao.save(imRoomUserShip);
        if(!result){
            return null;
        }
        ImRoomUserShipResponseDto imRoomUserShipResponseDto = ImRoomUserShipResponseDto.build().clone(imRoomUserShip);
        return imRoomUserShipResponseDto;


    }

    public boolean saveBatchImRoomUserShip(Collection<ImRoomUserShipRequestDto> entityList, int batchSize) {
        if(null == entityList || entityList.size() !=  batchSize){
            return false;
        }
        List<ImRoomUserShip> list = new ArrayList<>();
        entityList.forEach(e -> list.add(ImRoomUserShip.build().clone(e)));
        boolean result = imRoomUserShipDao.saveBatch(list,batchSize);
        return result;
    }


    public boolean saveOrUpdateBatchImRoomUserShip(Collection<ImRoomUserShipRequestDto> entityList, int batchSize) {
        if(null == entityList || entityList.size() != batchSize ){
            return false;
        }
        List<ImRoomUserShip> list = new ArrayList<>();
        entityList.forEach(e -> list.add(ImRoomUserShip.build().clone(e)));
        boolean result = imRoomUserShipDao.saveOrUpdateBatch(list,batchSize);
        return result;
    }


    public boolean updateBatchById(Collection<ImRoomUserShipRequestDto> entityList, int batchSize) {
        if(null == entityList || entityList.size() != batchSize ){
            return false;
        }
        List<ImRoomUserShip> list = new ArrayList<>();
        entityList.forEach(e -> list.add(ImRoomUserShip.build().clone(e)));
        boolean result =  imRoomUserShipDao.updateBatchById(list,batchSize);
        return result;
    }

    /**
     * 更新群与用户关系同时更新数据库和缓存的实现方法
     * @param imRoomUserShipRequestDto  ImRoomUserShipResponseDto
     * @return
     */
    public boolean updateImRoomUserShip(ImRoomUserShipRequestDto imRoomUserShipRequestDto){

          if(null ==  imRoomUserShipRequestDto){
              return false;
          }

        ImRoomUserShip imRoomUserShip = ImRoomUserShip.build().clone(imRoomUserShipRequestDto);

        return imRoomUserShipDao.updateById(imRoomUserShip);


    }







    /**
     * 通过主键ID删除对象信息实现缓存和数据库,同时删除的方法
     * @param  idList
     * @return
     */
    public int delImRoomUserShipByIds(List<Long> idList){
        boolean result = false;
        if(null == idList){
            return ResultEnum.FAIL.id();
        }
        if( idList.size() == 1) {
            result = imRoomUserShipDao.removeById(idList.get(0));
        }else {
            result =  imRoomUserShipDao.removeByIds(idList);
        }
        if(result){
            return ResultEnum.SUCCESS.id();
        }
        return ResultEnum.FAIL.id();

    }


    /**
     * 通过主键ID更新对象群与用户关系实现缓存和数据库更新的方法
     * @param  imRoomUserShipId
     * @return
     */
    public ImRoomUserShipResponseDto getImRoomUserShipById(long imRoomUserShipId){
        if(imRoomUserShipId < 0 ){
            return null;
        }
        ImRoomUserShip imRoomUserShip =  imRoomUserShipDao.getById(imRoomUserShipId);
        if(imRoomUserShip == null){
            return null;
        }
        ImRoomUserShipResponseDto imRoomUserShipResponseDto = ImRoomUserShipResponseDto.build().clone(imRoomUserShip);

        return imRoomUserShipResponseDto ;

    }

    @Override
    public List<ImRoomUserShipResponseDto> getImRoomUserShipByPage(BasePage page) {
        return null;
    }


    /**
    * 查询条件
    */
    public QueryWrapper<ImRoomUserShip> checkQueryCondition(BasePage basePage) {
        QueryWrapper<ImRoomUserShip> queryWrapper = new QueryWrapper<>();
        ImRoomUserShipRequestDto imRoomUserShipRequestDto = (ImRoomUserShipRequestDto) basePage.getParamObject();
        if(imRoomUserShipRequestDto.getRoomId() > 0){
            queryWrapper.eq("room_id",imRoomUserShipRequestDto.getRoomId());
        }
        if(StringUtils.isNotBlank(imRoomUserShipRequestDto.getNickName())){
            queryWrapper.like("nick_name",imRoomUserShipRequestDto.getNickName());
        }
        queryWrapper.eq("status",1);
        queryWrapper.orderByDesc("user_role");
        return queryWrapper;
    }


    /**
     * 通过分页获取ImRoomUserShip信息实现查找缓存和数据库的方法
     * @param basePage BasePage
     * @return
     * @author suven
     * @date 2021-05-11 15:34:25
     */
    public List<ImRoomUserShipResponseDto> getImRoomUserShipByPage(
            ResponseResultList<ImRoomUserShipResponseDto> responseResultList, BasePage basePage){


        List<ImRoomUserShipResponseDto> resDtoList = new ArrayList<>();
        if(basePage == null){
            return resDtoList;
        }
        //分页对象        PageHelper
        IPage<ImRoomUserShip> iPage = new Page<>(basePage.getPageNo(), basePage.getRealPageSize());
        QueryWrapper<ImRoomUserShip> queryWrapper = checkQueryCondition(basePage);

        IPage<ImRoomUserShip> page = imRoomUserShipDao.page(iPage, queryWrapper);
        if(null == page){
            return resDtoList;
        }

        List<ImRoomUserShip>  list = page.getRecords();
        if(null == list || list.isEmpty()){
            return resDtoList;
        }
        list.forEach(imRoomUserShip -> {
                ImRoomUserShipResponseDto imRoomUserShipResponseDto = ImRoomUserShipResponseDto.build().clone(imRoomUserShip);

            resDtoList.add(imRoomUserShipResponseDto);
        });
        responseResultList.setTotal((int) page.getTotal());
        return resDtoList;


    }

    /**
     * 通过分页获取ImRoomUserShip信息实现查找缓存和数据库的方法
     * @param basePage BasePage
     * @return
     * @author suven
     * @date 2021-05-11 15:34:25
     */
    public ResponseResultList<ImRoomUserShipResponseDto> getImRoomUserShipByNextPage(BasePage basePage){
        ResponseResultList<ImRoomUserShipResponseDto> responseResultList = ResponseResultList.build();
        List<ImRoomUserShipResponseDto>  list = this.getImRoomUserShipByPage(responseResultList,basePage);
        if(null == list ){
            list = new ArrayList<>();
        }
        boolean isNext =  basePage.isNextPage(list);
        responseResultList.toIsNextPage(isNext).toList(list);
        return responseResultList;

    }

    public PageUtils queryPage(Map<String, Object> params) {
        IPage iPage =  new Query<ImRoomUserShip>().getPage(params);
        QueryWrapper<ImRoomUserShip> queryWrapper = new QueryWrapper<>();
        IPage<ImRoomUserShip> page = imRoomUserShipDao.page(iPage,queryWrapper);
        return new PageUtils(page);
    }


    /**
     * 保存群与用户关系同时更新数据库和缓存的实现方法
     * @return
     */
    public ImRoomUserShip  setImRoomUserShip(){
        ImRoomUserShip imRoomUserShip = new ImRoomUserShip();
        /**
 			//imRoomUserShip.setCreateDate (Date createDate);
 			//imRoomUserShip.setModifyDate (Date modifyDate);
 			//imRoomUserShip.setStatus (int status);
 			//imRoomUserShip.setRoomId (long roomId);
 			//imRoomUserShip.setUserId (long userId);
 			//imRoomUserShip.setNickName (String nickName);
 			//imRoomUserShip.setUserRole (int userRole);
 			//imRoomUserShip.setRoomSet (int roomSet);
 			//imRoomUserShip.setRemarks (String remarks);
		**/

        return imRoomUserShip;
    }

    public boolean saveData(InputStream initialStream) {
        return ExcelUtils.readExcel(initialStream,imRoomUserShipDao, ImRoomUserShip.class,0);
    }

    @Override
    public List<ImRoomUserShipResponseDto> getImRoomUserShipByUserId(long userId) {
        List<ImRoomUserShipResponseDto> responseDtoList = new ArrayList<>();
        List<ImRoomUserShip> list = imRoomUserShipDao.selectByUser(userId);
        if( list == null || list.isEmpty() ){
            return responseDtoList;
        }
        responseDtoList = IterableConverter.convertList(list,ImRoomUserShipResponseDto.class);

        return responseDtoList;
    }

    /**
     * 查询某个用户，所有好友列表
     * @param userId
     * @return
     */
    public List<ImRoomUserShipResponseDto> selectListByUserId(long userId){
        List<ImRoomUserShip> list = imRoomUserShipDao.selectListByUserId( userId);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        List<ImRoomUserShipResponseDto> lists = new ArrayList<>();
        list.forEach(e->{
            lists.add(ImRoomUserShipResponseDto.build().clone(e));
        });
        return lists;
    }


    /**
     * 查询某个群某个用户关系
     * @param userId
     * @param roomId
     * @return
     */
    public ImRoomUserShipResponseDto selectRoomFriend(long userId,long roomId){
        ImRoomUserShip imUserFriend = imRoomUserShipDao.selectRoomFriend( userId, roomId);
        if(imUserFriend == null){
            return null;
        }
        return ImRoomUserShipResponseDto.build().clone(imUserFriend);
    }

    /**
     * 查询某个群，所有好友
     * @param roomId
     * @return
     */
    public List<ImRoomUserShipResponseDto> selectListByRoomId(long roomId){
        List<ImRoomUserShip> list = imRoomUserShipDao.selectListByRoomId( roomId);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        List<ImRoomUserShipResponseDto> lists = new ArrayList<>();
        list.forEach(e->{
            lists.add(ImRoomUserShipResponseDto.build().clone(e));
        });
        return lists;
    }

    /**
     * 查询某个群，所有好友
     * @param roomId
     * @return
     */
    public Map<Long,ImRoomUserShipResponseDto> selectMapByRoomId(long roomId){
        List<ImRoomUserShip> list = imRoomUserShipDao.selectListByRoomId( roomId);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        Map<Long,ImRoomUserShipResponseDto> map = new HashMap<>();
        list.forEach(e->{
            map.put(e.getUserId(),ImRoomUserShipResponseDto.build().clone(e));
        });
        return map;
    }

    /**
     * 查询某个群，所有好友
     * @param imRoomUser
     * @return
     */
    public List<ImRoomUserShipResponseDto> selectListByRoomId(ImRoomUserShipRequestDto imRoomUser){
        ImRoomUserShip imRoomUserShip = ImRoomUserShip.build().clone(imRoomUser);
        List<ImRoomUserShip> list = imRoomUserShipDao.selectListByRoomId( imRoomUserShip);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        List<ImRoomUserShipResponseDto> lists = new ArrayList<>();
        list.forEach(e->{
            lists.add(ImRoomUserShipResponseDto.build().clone(e));
        });
        return lists;
    }

    /**
     * 查询某个群，那些用户关系
     * @param userIds
     * @param roomId
     * @return
     */
    public List<ImRoomUserShipResponseDto> selectRoomFriend(Collection<Long> userIds,long roomId){
        List<ImRoomUserShip> list =  imRoomUserShipDao.selectRoomFriend( userIds, roomId);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        List<ImRoomUserShipResponseDto> lists = new ArrayList<>();
        list.forEach(e->{
            lists.add(ImRoomUserShipResponseDto.build().clone(e));
        });
        return lists;
    }
}
